package com.mr.utils;

import ognl.Ognl;
import ognl.OgnlException;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.ConversionServiceFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangxingchao
 * @date: 2010-7-23
 */
public class OgnlUtils {
    private static final ConversionService CONVERSION_SERVICE = ConversionServiceFactory.createDefaultConversionService();

    public static Parser newParser(Map<String, Object> dataRoot) {
        return new Parser(dataRoot);
    }

    public static <T> T getValue(String expression, Object dataRoot, Class<T> targetClazz) throws OgnlException {
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("root", dataRoot);
        String expr = "root." + expression;
        Object result = Ognl.getValue(expr, root);
        return CONVERSION_SERVICE.convert(result, targetClazz);
    }

    public static class Parser {
        private Map<String, Object> dataRoot;

        private Parser(Map<String, Object> dataRoot) {
            this.dataRoot = dataRoot;
        }

        public <T> T parse(String expression, Class<T> targetClazz ) throws OgnlException {
            Object result = Ognl.getValue(expression, dataRoot);

            return CONVERSION_SERVICE.convert(result, targetClazz);
        }
    }
}
